<script setup lang="ts">
import type { BareMetalNodeModel } from '@/apis/model/node'
import { getComputeIpSubnetListApi } from '@/apis/modules/computedIp'
import {
  addBaremetalNodeApi,
  getBaremetalNodeDetailApi,
  getManageRegionsListApi,
  updateBaremetalNodeApi,
} from '@/apis/modules/node'
import { getSwitcherListApi } from '@/apis/modules/switcher'
import { Message } from '@arco-design/web-vue'

interface IEmit {
  (e: 'success'): void
}

interface IProps {
  record?: BareMetalNodeModel
}
const props = defineProps<IProps>()
const emit = defineEmits<IEmit>()
const visible = defineModel<boolean>('visible', { required: true })
const formRef = ref()
const formData = reactive({
  id: '',
  region_id: '',
  ipmi: '',
  manage_switcher_id: '',
  switch_manage_port: '',
  external_switcher_id: '',
  switch_external_port: '',
  external_mac: '',
  ipmi_user: '',
  ipmi_password: '',
  tag: '',
})
const formRules: { [key in keyof typeof formData]?: FieldRule[] } = {
  region_id: [{ required: true, message: '请选择所属区域' }],
  ipmi: [
    { required: true, message: '请输入IPMI地址' },
    { type: 'ip', message: 'IPMI地址格式不正确' },
  ],
  manage_switcher_id: [{ required: true, message: '请选择交换机' }],
  switch_manage_port: [{ required: true, message: '请输入交换机端口' }],
  external_switcher_id: [{ required: true, message: '请选择交换机' }],
  switch_external_port: [{ required: true, message: '请输入交换机端口' }],
  external_mac: [{ required: true, message: '请输入外网MAC地址' }],
  ipmi_user: [{ required: true, message: '请输入用户名' }],
  ipmi_password: [{ required: true, message: '请输入密码' }],
}
const regions = ref<LabelValue[]>([])
async function getRegions() {
  const res = await getManageRegionsListApi({ offset: 0, limit: 500 })
  regions.value
    = res.list?.map((item) => {
      const name = JSON.parse(item.name ?? '')
      return { label: name['zh-CN'], value: item.id! }
    }) || []
}
onMounted(getRegions)
const switchList = ref<LabelValue[]>([])
async function getSwitchList() {
  if (!formData.region_id) {
    return
  }
  const res = await getSwitcherListApi({
    limit: '500',
  })
  switchList.value = (res.list || []).map((item) => {
    return {
      label: item.name!,
      value: item.id!,
      disabled: formData.region_id !== item.region_id,
    }
  })
}
watchEffect(getSwitchList)

const loading = ref(false)
const subnets = ref<LabelValue<string>[]>([])
async function getSubnets(regionId: string) {
  if (!regionId) {
    return
  }
  subnets.value = []
  const res = await getComputeIpSubnetListApi({ region_id: regionId })
  const list = res?.list ?? []
  subnets.value = list.map((item) => {
    return { label: item.name!, value: item.uuid! }
  })!
}

function handleRegionChange() {
  formData.manage_switcher_id = ''
  formData.external_switcher_id = ''
  getSubnets(formData.region_id)
}

const title = computed(() => {
  return props.record?.id ? '编辑节点' : '新建节点'
})

// 表单提交
async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error) {
    return false
  }

  const data = { ...formData }
  const fn = props.record?.id ? updateBaremetalNodeApi : addBaremetalNodeApi
  return fn(data)
    .then(() => {
      emit('success')
      Message.success(props.record?.id ? '更新成功' : '新建成功')
    })
    .finally(() => {
      loading.value = false
    })
}

async function handleOpen() {
  if (props.record?.id) {
    loading.value = true
    const res = await getBaremetalNodeDetailApi({ id: props.record?.id })
    formData.region_id = res.info?.region_id ?? ''
    await getSubnets(formData.region_id)
    Object.assign(formData, res.info ?? {})
    loading.value = false
  }
}

// 弹窗关闭
function handleClose() {
  formRef.value?.resetFields()
}
</script>

<template>
  <a-drawer
    v-model:visible="visible"
    :title="title"
    :width="480"
    ok-text="保存"
    :ok-loading="loading"
    unmount-on-close
    :mask-closable="false"
    @before-close="handleClose"
    @before-open="handleOpen"
    @before-ok="handleSubmit"
  >
    <a-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      layout="vertical"
    >
      <a-form-item
        label="所属区域"
        field="region_id"
        required
        asterisk-position="end"
        hide-asterisk
      >
        <a-select
          v-model="formData.region_id"
          placeholder="请选择所属区域"
          :options="regions"
          @change="handleRegionChange"
        />
      </a-form-item>
      <a-form-item
        label="外网MAC地址"
        field="external_mac"
        required
        asterisk-position="end"
        hide-asterisk
      >
        <a-input
          v-model="formData.external_mac"
          placeholder="请输入外网MAC地址"
          show-word-limit
          :max-length="20"
        />
      </a-form-item>
      <a-form-item
        label="交换机(管理网)"
        field="manage_switcher_id"
        required
        asterisk-position="end"
        hide-asterisk
      >
        <a-select
          v-model="formData.manage_switcher_id"
          placeholder="请选择交换机"
          :options="switchList"
          :disabled="!formData.region_id"
        />
      </a-form-item>
      <a-form-item
        label="交换机端口(管理网)"
        field="switch_manage_port"
        required
        asterisk-position="end"
        hide-asterisk
      >
        <a-input
          v-model="formData.switch_manage_port"
          placeholder="请输入交换机端口"
          show-word-limit
          :max-length="20"
        />
      </a-form-item>
      <a-form-item
        label="交换机(外网)"
        field="external_switcher_id"
        required
        asterisk-position="end"
        hide-asterisk
      >
        <a-select
          v-model="formData.external_switcher_id"
          placeholder="请选择交换机"
          :options="switchList"
          :disabled="!formData.region_id"
        />
      </a-form-item>
      <a-form-item
        label="交换机端口(外网)"
        field="switch_external_port"
        required
        asterisk-position="end"
        hide-asterisk
      >
        <a-input
          v-model="formData.switch_external_port"
          placeholder="请输入交换机端口"
          show-word-limit
          :max-length="20"
        />
      </a-form-item>
      <a-form-item
        label="IPMI地址"
        field="ipmi"
        required
        asterisk-position="end"
        hide-asterisk
      >
        <a-input
          v-model="formData.ipmi"
          placeholder="请输入IPMI地址"
          show-word-limit
          :max-length="256"
        />
      </a-form-item>
      <a-form-item
        label="用户名"
        field="ipmi_user"
        required
        asterisk-position="end"
        hide-asterisk
      >
        <a-input
          v-model="formData.ipmi_user"
          :input-attrs="{
            name: 'ipmi_user',
          }"
          placeholder="请输入用户名"
          :max-length="30"
          show-word-limit
        />
      </a-form-item>

      <a-form-item
        label="密码"
        field="ipmi_password"
        required
        asterisk-position="end"
        hide-asterisk
      >
        <a-input-password
          v-model="formData.ipmi_password"
          placeholder="请输入密码"
          :max-length="64"
          name="reIpmiPassword"
        />
      </a-form-item>
      <a-form-item
        label="节点标签"
        field="tag"
      >
        <a-input
          v-model="formData.tag"
          placeholder="请输入节点标签"
          :max-length="20"
          show-word-limit
        />
        <template #help>
          <div class="mt-1 text-xs text-color-3">
            示例: 名称-RACK-UUID-RU
          </div>
        </template>
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<style lang="less" scoped></style>
